package com.xiashitech.agent.service;

import com.xiashitech.agent.config.StartConfig;
import com.xiashitech.agent.dto.UserRequest;
import com.xiashitech.agent.instrumentation.base.context.XSBaggage;
import com.xiashitech.agent.instrumentation.httprequest.XSHttpServletResponseWrapper;
import com.xiashitech.agent.utils.JsonUtil;
import io.opentelemetry.javaagent.bootstrap.internal.InstrumentationConfig;

import java.io.ByteArrayOutputStream;
import java.io.CharArrayWriter;
import java.io.IOException;

public class DesensitizeService {

    public static String getResponseJsonData(XSHttpServletResponseWrapper xsResponse) {
        String oriJson = "";
        if (xsResponse != null) {
            byte[] byteArray = xsResponse.getByteArray();
            char[] charArray = xsResponse.getCharArray();
            if (byteArray.length > 0) {
                oriJson = new String(byteArray);
            } else if (charArray.length > 0) {
                oriJson = new String(charArray);
            }
        }
        return oriJson;
    }

    public static void desensitizeResponseJsonData(UserRequest userRequest, XSHttpServletResponseWrapper xsResponse, String jsonString) throws IOException {
        if (xsResponse == null) return;
        byte[] responseWrapperByteArray = xsResponse.getByteArray();
        char[] responseWrapperCharArray = xsResponse.getCharArray();

        XSBaggage[] baggagesWithCurrentAndConfluence = XSBaggage.currentWithConfluence();
        for (XSBaggage xsBaggage : baggagesWithCurrentAndConfluence) {
            if (xsBaggage != null) {
                String endpointApiBack = xsBaggage.getEntryValue("endpoint-api-back");
                if (jsonString != null && endpointApiBack != null) {
                    String[] endpointApiBacks = endpointApiBack.split("#");
                    for (String endpointApiBackItem : endpointApiBacks) {
                        String jsonPath = jsonString;
                        String apiName = null;
                        String[] desenseAction = endpointApiBackItem.split("&");
                        for (int i = 0; i < desenseAction.length; i++) {
                            if (i == 0) {
                                apiName = desenseAction[0];
                                if (!userRequest.getEndpointApi().equals(apiName)) {
                                    break;
                                } else {
                                    continue;
                                }
                            }
                            String[] desenseActionItem = desenseAction[i].split("=");
                            String patchPath = desenseActionItem[0];
                            String[] patchPathItem = desenseActionItem[1].split(",");
                            String isExecute = patchPathItem[0];
                            String regular = patchPathItem[1];
                            String replaceSymbol = patchPathItem[2];
                            String systemId = patchPathItem[3];
                            //执行脱敏
                            if ("true".equals(isExecute) && StartConfig.getParamValueFromKey(StartConfig.systemId).equals(systemId)) {
                                if (responseWrapperByteArray.length > 0) {
                                    jsonPath = JsonUtil.jsonPatch(jsonPath, patchPath, regular, replaceSymbol);
                                    if (jsonPath != null) {
                                        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(jsonPath.getBytes().length);
                                        String charset = InstrumentationConfig.get().getString("xs.charset.textcontent");
                                        if (charset != null) {
                                            byteArrayOutputStream.write(jsonPath.getBytes(charset));
                                        } else {
                                            byteArrayOutputStream.write(jsonPath.getBytes());
                                        }
                                        xsResponse.setByteArrayOutputStream(byteArrayOutputStream);
                                        xsResponse.setContentLength(byteArrayOutputStream.size());
                                    }
                                } else if (responseWrapperCharArray.length > 0) {
                                    jsonPath = JsonUtil.jsonPatch(jsonPath, patchPath, regular, replaceSymbol);
                                    if (jsonPath != null) {
                                        CharArrayWriter charArrayWriter = new CharArrayWriter(jsonPath.length());
                                        charArrayWriter.write(jsonPath);
                                        xsResponse.setCharArrayWriter(charArrayWriter);
                                        xsResponse.setContentLength(charArrayWriter.size());
                                    }
                                }
                            }

                        }

                    }

                }
            }
        }

    }

}
